package com.travel.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.travel.entity.Scenic;
import com.travel.entity.User;
import com.travel.service.UserService;
import com.travel.service.impl.UserServiceImpl;
import com.travel.util.PhoneCode;

/**
 * Servlet implementation class UserServlet
 * @author zourenhe
 */
@MultipartConfig
@WebServlet("/user")
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private UserService userService = new UserServiceImpl();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		String  op = request.getParameter("op");
		if ("UserLogout".equals(op)) {
			doLogout(request,response);
		}else if ("register".equals(op)) {
			// 注册
			doUserRegister(request,response);
		} else if ("login".equals(op)) {
			// 登录
			doLogin(request,response);
		}else if ("existOfUserName".equals(op)) {
			// 判断用户名是否存在
			doExistOfUserName(request,response);
		}else if("getCode".equals(op)) {
			doGetCode(request,response);
		}
				
	}


	private void doGetCode(HttpServletRequest request, HttpServletResponse response) {
		String userPhone=request.getParameter("phone");
		PhoneCode.getPhonemsg(userPhone);	
	}

	private void doExistOfUserName(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 调用业务层
				String userName = request.getParameter("userName");
				List<User> list = userService.findByNameAndPassword(userName);
				if (list.isEmpty()) { // 空
					// 用户名不存在
					// 响应文本数据
					response.getWriter().print("no exist"); // 不存在
				} else {
		           // 用户名存在
				   // 响应文本数据
				   response.getWriter().print("exist"); // 存在
				}
		
	}

	private void doUserRegister(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {		
		String userName = request.getParameter("username");
		String userPassword = request.getParameter("password");
		String phone = request.getParameter("phone");
		String userPasswordMD5 = MD5Utils.md5(userPassword);
		User user = new User(null, userName, userPasswordMD5, null, null, null, phone, null);	
		//收到的验证码
		String code=PhoneCode.code;
		//客户输入的验证码
		String verifyCode=request.getParameter("verifyCode");
		//System.out.println("验证码："+code+"输入的验证码"+verifyCode);
		if(code.equals(verifyCode)) {
			if (userService.register(user)) {
				response.getWriter().print("success");	
			}
		}else {
			response.getWriter().print("CodeFail");
		}
//		if (userService.register(user)) {
//			response.getWriter().print("success");	
//		}
		
	}

	private void doLogout(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		// 清除session用户信息
		HttpSession session = request.getSession();
		session.removeAttribute("user");
		response.sendRedirect("front/userLogin.jsp");
	}

	private void doLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		String userName = request.getParameter("userName");
		String userPassword = request.getParameter("userPassword");
//		String userPasswordMD5 = MD5Utils.md5(userPassword);
		
		
		System.out.println(userPassword.length());
		String userPasswordMD5 = null;
		if (!(userPassword.length() == 32)) {
			userPasswordMD5 = MD5Utils.md5(userPassword);
		} else {
			userPasswordMD5 = userPassword;
		}
		
		System.out.println(userPasswordMD5);
		
		System.out.println(userName +"" + userPassword);
		
		
		
		// 调用业务层
		List<User> user = userService.login(userName, userPasswordMD5);
		
		
		System.out.println(user);
		// 响应内容类型
		response.setContentType("application/json;charset=utf-8");
		if (user.isEmpty()) {
			// 登录失败
//			ObjectMapper objectMapper = new ObjectMapper();
//			String json = objectMapper.writeValueAsString("fail");
			response.getWriter().print("fail");
		}else {
			// 登录成功
			// 存储到session会话
			HttpSession session = request.getSession();
			session.setAttribute("user", user);
			// 响应
//			ObjectMapper objectMapper = new ObjectMapper();
//			String json = objectMapper.writeValueAsString("success");
			session.setMaxInactiveInterval(300); // 5分钟
			session.setAttribute("user",user.get(0));
			// session.setAttribute(session.getId(), list.get(0));
			
			// 判断是否记住密码
			String remeberme = request.getParameter("remeberme");// 有选中返回on,未选择则返回null
			System.out.println("选中状态" + remeberme);
			
			// 将用户信息存储在cookie中,多用户,选择存储形式为username=password
			Cookie cookie = new Cookie(userName, userPasswordMD5);
			if ("on".equals(remeberme)) {
				// 选择记住密码
				// 设置年龄
				cookie.setMaxAge(60*60*24); // 24小时
				// 添加到HTTP的响应体中
				response.addCookie(cookie);
			} else {
				// 选择不记住密码
				// 将当前用户的cookie信息删除
				// 设置年龄
				cookie.setMaxAge(0); // 24小时
				// 添加到HTTP的响应体中
				response.addCookie(cookie);
			}
			
			response.getWriter().print("success");
			
		}
	}
}